package com.jvtd.demo.im;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.jvtd.base.JvtdActivity;
import com.jvtd.demo.R;
import com.jvtd.rong_im.listener.BaseTypingStatusListener;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/*
 * 会话界面Activity
 * Create by Jack Zhang
 */
public class ConversationActivity extends JvtdActivity
{
  private TextView tvTitle;

  private String mTitle;
  private String mTargetId;
  private Conversation.ConversationType mConversationType;

  private static final int NOTIFY_UPDATE_TITLE = 0x10;

  @SuppressLint("HandlerLeak")
  private Handler handler = new Handler()
  {
    @Override
    public void handleMessage(Message msg)
    {
      switch (msg.what)
      {
        case NOTIFY_UPDATE_TITLE:
          tvTitle.setText(String.valueOf(msg.obj));
          break;
      }
    }
  };

  @Override
  protected void bindView()
  {
    tvTitle = findViewById(R.id.tv_title);
    Toolbar mToolbar = findViewById(R.id.tool_bar);
    setToolbar(mToolbar, true);
  }

  @Override
  protected void getLayout()
  {
    setContentView(R.layout.activity_conversation);
  }

  @Override
  protected void initViewAndData()
  {
    /* 从 intent 携带的数据里获取 targetId 和会话类型*/
    Uri uri = getIntent().getData();
    if (uri == null)
    {
      finish();
      return;
    }
    mTitle = uri.getQueryParameter("title");
    tvTitle.setText(mTitle);
    mTargetId = uri.getQueryParameter("targetId");
    String lastPathSegment = uri.getLastPathSegment();
    if (lastPathSegment != null)
      mConversationType = Conversation.ConversationType.valueOf(lastPathSegment.toUpperCase());

    // 通过 rc_configuration.xml 里的开关开启输入状态提醒的功能，目前仅支持单聊。默认 true 是开启，设置为 false 为关闭。
    if (mConversationType == Conversation.ConversationType.PRIVATE)
      RongIMClient.setTypingStatusListener(new BaseTypingStatusListener(mTitle, mTargetId, mConversationType, titleContent ->
      {
        Message msg = handler.obtainMessage();
        msg.what = NOTIFY_UPDATE_TITLE;
        msg.obj = titleContent;
        handler.sendMessage(msg);
      }));
  }
}
